<?php
namespace app\controller\back;

use app\common\controller\_AdminController;
use app\model\Article;
use app\model\ArticleType as Type;
use app\model\ArticleTag as Tag;
use think\Validate;

class ArticleController extends _AdminController
{	
	protected $rule = [
		'id|编号'					=> 'integer',
		'title|标题'					=> 'chsDash|length:1,50',
		'cover|封面'					=> "url|length:3,200",
		'content|内容'				=> 'requireCallback:checkContent',
		'type_id|类型'				=> 'integer',
		'status|状态'				=> 'in:0,1',
		'hot_level|推荐状态'			=> 'in:1,2,3',
		'comment_status|评论状态'		=> 'in:0,1',

		'user_name|用户名'			=> 'alphaDash',
		'user_type|用户类型'			=> 'in:1,2',
		'start|起始时间'				=> 'dateFormat:Y-m-d',
        'end|结束时间'				=> 'dateFormat:Y-m-d',

        'pid|上级编号'				=> 'integer',
		'name|名称'					=> 'chsDash|length:2,50',
		'sort|排序'					=> 'integer',
		'color|颜色值'				=> 'alphaNum|length:6',

		'page|页码'         			=> 'integer',
        'size|条数'        			=> 'integer',
	];
	
	protected $scene = [
		// 文章
		'create'			=> ['title','cover','content','type_id','status','hot_level','comment_status'],
		'update'			=> ['id','title','cover','content','type_id','status','hot_level','comment_status'],
        'delete'            => ['id'],
        'list'              => ['title','type_id','status','hot_level','start','end','user_name','user_type','page','size'],
        // 文章类型
        'typeCreate'		=> ['pid','name','sort'],
        'typeUpdate'		=> ['id','pid','name','sort'],
        'typeDelete'		=> ['id'],
        'typelist'			=> [],


	];

	protected function initialize()
	{	
		parent::initialize();
		switch ($this->action) {
			// 文章
			case 'create':
				$this->appendRule('title','require|unique:article');
				$this->replaceRule('content','requireCallback:checkContent','require');
				$this->appendRule('type_id','require|checkTypeById');
				break;
			case 'update':
				$this->appendRule('id','require|checkArticleById');
				$this->appendRule('title','unique:article');
				$this->appendRule('type_id','checkTypeById');
				break;
            case 'delete':
                $this->appendRule('id','require|checkArticleById');
                break;
            case 'list':
                $this->appendRule('type_id','checkTypeById');
                break;
            // 文章类型
            case 'typeCreate':
            	$this->appendRule('pid','checkTypeByPid');
				$this->appendRule('name','require|unique:article_type');
				break;
			 case 'typeUpdate':
            	$this->appendRule('id','checkTypeById');
				$this->appendRule('pid','checkTypeByPid');
				$this->appendRule('name','unique:article_type');
				break;
			case 'typeDelete':
                $this->appendRule('id','require|checkTypeDel');
                break;

			default:
				# code...
				break;
		}
		$this->check();
	}
	/**
	 * @api {POST} /back/config/create 创建文章
	 * @apiVersion 0.0.1
	 * @apiGroup Back-config
	 *
	 * @apiParam {String} alias 别名
	 * @apiParam {String} name 名称
	 * @apiParam {Number} [sort=0] 排序
	 * @apiParam {String} [desc] 描述
	 * @apiParam {String} value 值
	 * @apiParam {String} type 类型
	 *
	 * @apiParamExample {json} Request-Example:
	 * {
	 *     "alias": "zcx",
	 *     "name": "ad222",
	 *     "sort": "1",
	 *     "desc": "asds",
	 *     "value": "1",
     *     "type": "number",
	 * }
	 * 
	 * @apiSuccessExample {json} 成功返回:
	 * HTTP/1.1 200 OK
	 * {
	 *     "code":200,
	 *     "msg":"操作成功",
	 *     "data": []
	 * }
	 */
	public function createAction()
	{   
		$this->data['user_id'] = $this->user->id;
		$this->data['user_type'] = $this->user->type;
		$this->data['user_name'] = $this->user->name;
		Article::doSave($this->data);
        return parent::resSuccess();
	}


	/**
	 * @api {POST} /back/config/update 修改配置
	 * @apiVersion 0.0.1
	 * @apiGroup Back-config
	 *
	 * @apiParam {Number} id 编号
	 * @apiParam {String} [alias] 别名
	 * @apiParam {String} [name] 名称
	 * @apiParam {Number} [sort=0] 排序
	 * @apiParam {String} [desc] 描述
	 * @apiParam {String} [value] 值
	 * @apiParam {String} [type] 类型
     *
     * @apiParamExample {json} Request-Example:
     * {
	 *     "alias": "zcx",
	 *     "name": "ad222",
	 *     "sort": "1",
	 *     "desc": "asds",
	 *     "value": "1",
     *     "type": "number",    
     * }
     * 
	 * @apiSuccessExample {json} 成功返回:
	 * HTTP/1.1 200 OK
	 * {
	 *     "code":200,
	 *     "msg":"操作成功",
	 *     "data": []   
	 * }
	 */
	public function updateAction()
	{   
		$this->data['user_id'] = $this->user->id;
		$this->data['user_type'] = $this->user->type;
		Article::doSave($this->data,$this->id);
        return parent::resSuccess();
	}

	/**
	 * @api {POST} /back/config/delete 删除配置
	 * @apiVersion 0.0.1
	 * @apiGroup Back-config
	 *
	 * @apiParam {Number} id 编号
     *
     * @apiParamExample {json} Request-Example:
     * {
     *     "id": "1",
     * }
     * 
	 * @apiSuccessExample {json} 成功返回:
	 * HTTP/1.1 200 OK
	 * {
	 *     "code":200,
	 *     "msg":"操作成功",
	 *     "data": []   
	 * }
	 */
	public function deleteAction()
	{   
		Article::doDelete($this->id);
        return parent::resSuccess();
	}

	/**
	 * @api {POST} /back/config/list 配置列表
	 * @apiVersion 0.0.1
	 * @apiGroup Back-config
	 * 
	 * @apiSuccess {Number} id 编号
	 * @apiSuccess {String} alias 别名
	 * @apiSuccess {String} name 名称
	 * @apiSuccess {Number} sort 排序
	 * @apiSuccess {String} desc 描述
	 * @apiSuccess {String} value 值
	 * @apiSuccess {String} type 类型
	 * @apiSuccess {String} create_time 创建时间
	 * @apiSuccess {String} update_time 更新时间
	 * @apiSuccess {String} count 总条数
     * 
	 * @apiSuccessExample {json} 成功返回:
	 * HTTP/1.1 200 OK
	 * {
	 *     "code":200,
	 *     "msg":"操作成功",
	 *     "data": [{
     *         "id": 39,
	 *         "alias": "zcx",
	 *         "name": "ad222",
	 *         "sort": "1",
	 *         "desc": "asds",
	 *         "value": "1",
     *         "type": "number",  
     *         "create_time": "2019-04-09 17:24:19",
     *         "update_time": "2019-04-09 17:24:19",
	 *     }],
	 *     "count": 6
	 * }
	 */
	public function listAction()
	{   
		$cond = Article::getStatusCond($this->data);
		if(isset($this->data['title']) && strlen($this->data['title']) > 0){
            $cond[] = ['','exp',Article::raw("locate('{$this->data['title']}',title)>0")];
        }
        if(!empty($this->data['type_id'])){
            $cond[] = ['type_id','=',$this->data['type_id']];
        }
        if(!empty($this->data['hot_level'])){
            $cond[] = ['hot_level','=',$this->data['hot_level']];
        }
		if(isset($this->data['user_name']) && strlen($this->data['user_name']) > 0){
            $cond[] = ['','exp',Article::raw("locate('{$this->data['user_name']}',user_name)>0")];
        }
        if(!empty($this->data['user_type'])){
            $cond[] = ['user_type','=',$this->data['user_type']];
        }
        if(!empty($this->data['start'])){
            $cond[] = ['create_time','>=',strtotime($this->data['start'])];
        }
        if(!empty($this->data['end'])){
            $cond[] = ['create_time','<=',strtotime($this->data['end'])];
        }
		$list = Article::doList($cond,$this->page,$this->size);
		return parent::resSuccess($list);
	}

	/**
	 * @api {POST} /back/config/create 创建文章
	 * @apiVersion 0.0.1
	 * @apiGroup Back-config
	 *
	 * @apiParam {String} alias 别名
	 * @apiParam {String} name 名称
	 * @apiParam {Number} [sort=0] 排序
	 * @apiParam {String} [desc] 描述
	 * @apiParam {String} value 值
	 * @apiParam {String} type 类型
	 *
	 * @apiParamExample {json} Request-Example:
	 * {
	 *     "alias": "zcx",
	 *     "name": "ad222",
	 *     "sort": "1",
	 *     "desc": "asds",
	 *     "value": "1",
     *     "type": "number",
	 * }
	 * 
	 * @apiSuccessExample {json} 成功返回:
	 * HTTP/1.1 200 OK
	 * {
	 *     "code":200,
	 *     "msg":"操作成功",
	 *     "data": []
	 * }
	 */
	

	public function typeCreateAction()
	{   
		Type::doSave($this->data);
        return parent::resSuccess();
	}


	/**
	 * @api {POST} /back/config/update 修改配置
	 * @apiVersion 0.0.1
	 * @apiGroup Back-config
	 *
	 * @apiParam {Number} id 编号
	 * @apiParam {String} [alias] 别名
	 * @apiParam {String} [name] 名称
	 * @apiParam {Number} [sort=0] 排序
	 * @apiParam {String} [desc] 描述
	 * @apiParam {String} [value] 值
	 * @apiParam {String} [type] 类型
     *
     * @apiParamExample {json} Request-Example:
     * {
	 *     "alias": "zcx",
	 *     "name": "ad222",
	 *     "sort": "1",
	 *     "desc": "asds",
	 *     "value": "1",
     *     "type": "number",    
     * }
     * 
	 * @apiSuccessExample {json} 成功返回:
	 * HTTP/1.1 200 OK
	 * {
	 *     "code":200,
	 *     "msg":"操作成功",
	 *     "data": []   
	 * }
	 */
	public function typeUpdateAction()
	{   
		Type::doSave($this->data,$this->id);
        return parent::resSuccess();
	}

	/**
	 * @api {POST} /back/config/delete 删除配置
	 * @apiVersion 0.0.1
	 * @apiGroup Back-config
	 *
	 * @apiParam {Number} id 编号
     *
     * @apiParamExample {json} Request-Example:
     * {
     *     "id": "1",
     * }
     * 
	 * @apiSuccessExample {json} 成功返回:
	 * HTTP/1.1 200 OK
	 * {
	 *     "code":200,
	 *     "msg":"操作成功",
	 *     "data": []   
	 * }
	 */
	public function typeDeleteAction()
	{   
		Type::doDelete($this->id);
        return parent::resSuccess();
	}

	/**
	 * @api {POST} /back/config/list 配置列表
	 * @apiVersion 0.0.1
	 * @apiGroup Back-config
	 * 
	 * @apiSuccess {Number} id 编号
	 * @apiSuccess {String} alias 别名
	 * @apiSuccess {String} name 名称
	 * @apiSuccess {Number} sort 排序
	 * @apiSuccess {String} desc 描述
	 * @apiSuccess {String} value 值
	 * @apiSuccess {String} type 类型
	 * @apiSuccess {String} create_time 创建时间
	 * @apiSuccess {String} update_time 更新时间
	 * @apiSuccess {String} count 总条数
     * 
	 * @apiSuccessExample {json} 成功返回:
	 * HTTP/1.1 200 OK
	 * {
	 *     "code":200,
	 *     "msg":"操作成功",
	 *     "data": [{
     *         "id": 39,
	 *         "alias": "zcx",
	 *         "name": "ad222",
	 *         "sort": "1",
	 *         "desc": "asds",
	 *         "value": "1",
     *         "type": "number",  
     *         "create_time": "2019-04-09 17:24:19",
     *         "update_time": "2019-04-09 17:24:19",
	 *     }],
	 *     "count": 6
	 * }
	 */
	public function typeListAction()
	{   
		$list = Type::doList();
		return parent::resSuccess($list);
	}
	

	

	// 自定义规则
	protected function checkArticleById()
	{
		Validate::extend('checkArticleById', function ($value) {
			$article = Article::get($value);
			if(!$article){
				return '记录不存在';
			}
			return true;
		});
	}

	// 自定义规则
	protected function checkContent()
	{
		Validate::extend('checkContent', function () {
			
		});
	}

	// 自定义规则
	protected function checkTypeByPid()
	{
		Validate::extend('checkTypeByPid', function ($value) {
			if($value){
				$type = Type::where(['pid'=>0,'id'=>$value])->find();
				return $type?true:'上级不存在';
			}
			return true;
		});
	}

	// 自定义规则
	protected function checkTypeById()
	{
		Validate::extend('checkTypeById', function ($value) {
			$type = Type::get($value);
			return $type?true:'记录不存在';
		});
	}

	// 自定义规则
	protected function checkTypeDel()
	{
		Validate::extend('checkTypeDel', function ($value) {
			$type = Type::get($value);
			if(!$type){
				return '记录不存在';
			}
			if($type->status == Type::STATUS_ENABLE){
				return '删除前请先禁用';
			}
			if($type->pid == 0){
				$sub = Type::where(['pid'=>$value])->find();
				if($sub){
					return '有下级数据,无法删除';
				}
			}
			$article = Article::where(['type_id'=>$value])->find();
			if($article){
				return '还有文章在使用,无法删除';
			}
			return true;
		});
	}

	
}
